﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace LynxWebLog
{
    public class BlogSupport
    {
        HttpClient client = ClientUtility.BlogAPIClient();
        public async Task CreateNewBlog(string userName, string blogName, RequestContext req)
        {
            string userPath = HttpContext.Current.Server.MapPath("~/BlogResources/" + userName);
            DirectoryInfo di = new DirectoryInfo(userPath);
            if (!di.Exists) {
                di.Create();
            }
            BlogInfo bi = new BlogInfo(userName + "_" + blogName, blogName,
                string.Format("Blogs/{0}/{1}", userName, blogName));
            //BlogInfo bi = new BlogInfo(userName + "_" + blogName, blogName,
            //    string.Format("{0}://{1}/{2}/Blogs/{3}/{4}", req.HttpContext.Request.Url.Scheme,
            //    req.HttpContext.Request.Url.Authority, HttpRuntime.AppDomainAppVirtualPath, userName, blogName));
            string blog = Path.Combine(userPath, blogName);
            DirectoryInfo db = new DirectoryInfo(blog);
            if (!db.Exists) {
                db.Create();
            }
            string license = (string)req.HttpContext.Application["__DefaultLicense"];

            HttpResponseMessage resp = await client.PostAsXmlAsync("api/BlogData", new BlogData(bi, userName, license));
            resp.EnsureSuccessStatusCode();

        }

        public void RenameUserBlog(string newName, string oldName, string userName)
        {

        }

        public async Task<bool> Exists(string userName)
        {
            List<BlogData> lbd = new List<BlogData>();
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogData/?$filter=username eq '" + userName + "'");
                resp.EnsureSuccessStatusCode();
                IEnumerable<BlogData> ibd = await resp.Content.ReadAsAsync<IEnumerable<BlogData>>();
                lbd = ibd.ToList();
            }
            catch { }
            return (lbd.Count > 0);
        }

        public async Task<bool> BlogExists(string userName, string blogName)
        {
            List<BlogData> lbd = new List<BlogData>();
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogData/?$filter=username eq '" + userName + "' and blogname eq '" + blogName + "'");
                resp.EnsureSuccessStatusCode();
                IEnumerable<BlogData> ibd = await resp.Content.ReadAsAsync<IEnumerable<BlogData>>();
                lbd = ibd.ToList();
            }
            catch { }
            return (lbd.Count > 0);
        }

        public async Task<Post> GetCurrentPost(string userName, string blogName)
        {
            Post bEntry = new Post();
            try {
                HttpResponseMessage bdResp = await client.GetAsync("api/BlogData/?$filter=username eq '" + userName + "' and blogname eq '" + blogName + "'");
                bdResp.EnsureSuccessStatusCode();
                BlogData bd = (await bdResp.Content.ReadAsAsync<IEnumerable<BlogData>>()).FirstOrDefault();
                if (bd != null) {

                    HttpResponseMessage resp = await client.GetAsync("api/CurrentPostData/?$filter=blogid eq '" + bd.blogid + "'");
                    resp.EnsureSuccessStatusCode();

                    IEnumerable<CurrentPostData> ipd = await resp.Content.ReadAsAsync<IEnumerable<CurrentPostData>>();
                    foreach (CurrentPostData p in ipd) {
                        HttpResponseMessage rpCat = await client.GetAsync("api/PostCategory/?$filter=postid eq " + p.postid);
                        rpCat.EnsureSuccessStatusCode();
                        List<string> sCat = new List<string>();
                        List<PostCategory> lpc = (await rpCat.Content.ReadAsAsync<IEnumerable<PostCategory>>()).ToList();
                        foreach (PostCategory cat in lpc) {
                            HttpResponseMessage rcd = await client.GetAsync("api/CategoryData/?$filter=categoryid eq " + cat.category);
                            rcd.EnsureSuccessStatusCode();
                            CategoryData cd = (await rcd.Content.ReadAsAsync<IEnumerable<CategoryData>>()).FirstOrDefault();
                            sCat.Add(cd.title);
                        }
                        p.categories = sCat.ToArray();
                    }
                    bEntry = new Post(ipd.FirstOrDefault());
                }
            }
            catch { }

            return bEntry;
        }

        public async Task<PageData> GetCurrentPage(string userName, string blogName, string pageName)
        {
            Page pEntry = new Page();
            HttpResponseMessage bdResp = await client.GetAsync("api/BlogData/?$filter=username eq '" + userName + "' and blogname eq '" + blogName + "'");
            bdResp.EnsureSuccessStatusCode();
            BlogData bd = (await bdResp.Content.ReadAsAsync<IEnumerable<BlogData>>()).FirstOrDefault();

            HttpResponseMessage bpResp = await client.GetAsync("api/PageData/?$filter=blogid eq '" + bd.blogid + "' and title eq '" + pageName + "'");
            bpResp.EnsureSuccessStatusCode();

            PageData pd = (await bpResp.Content.ReadAsAsync<IEnumerable<PageData>>()).FirstOrDefault();

            return pd;
        }

        public async Task<List<PageData>> GetPageIndex(string userName, string blogName)
        {
            List<PageData> pdIndex = new List<PageData>();
            HttpResponseMessage bdResp = await client.GetAsync("api/BlogData/?$filter=username eq '" + userName + "' and blogname eq '" + blogName + "'");
            bdResp.EnsureSuccessStatusCode();
            BlogData bd = (await bdResp.Content.ReadAsAsync<IEnumerable<BlogData>>()).FirstOrDefault();

            HttpResponseMessage bpResp = await client.GetAsync("api/PageData/?$filter=blogid eq '" + bd.blogid + "'");
            bpResp.EnsureSuccessStatusCode();

            pdIndex = (await bpResp.Content.ReadAsAsync<IEnumerable<PageData>>()).ToList();

            return pdIndex;
        }

        public async Task<List<PostData>> GetPostIndex(string userName, string blogName)
        {
            List<PostData> pdIndex = new List<PostData>();
            HttpResponseMessage bdResp = await client.GetAsync("api/BlogData/?$filter=username eq '" + userName + "' and blogname eq '" + blogName + "'");
            bdResp.EnsureSuccessStatusCode();
            BlogData bd = (await bdResp.Content.ReadAsAsync<IEnumerable<BlogData>>()).FirstOrDefault();

            HttpResponseMessage bpResp = await client.GetAsync("api/PostData/?$filter=blogid eq '" + bd.blogid + "'");
            bpResp.EnsureSuccessStatusCode();

            pdIndex = (await bpResp.Content.ReadAsAsync<IEnumerable<PostData>>()).ToList();

            return pdIndex;
        }
    }
}
